package com.banciyuan.bcywebview.utils.string;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;

import com.banciyuan.bcywebview.utils.http.HttpUtils;

import org.json.JSONObject;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.daoexample.model.AtUser;
import de.greenrobot.daoexample.model.Timeline;

/**
 * <br/>
 * String工具类. <br/>
 * 主要用于转换时间戳，替换html标签等
 * 需要别的功能请添加，一般不要直接修改
 *
 * @author hfxt2008
 */
public class StringUtil {

    public static String htmlDecoder(String src) {
        if (TextUtils.isEmpty(src)) {
            return "";
        }

        Spanned dst = Html.fromHtml(src);
        return dst.toString();
    }

    public static String getTimeDuration(int time) {
        String hs = "";
        String ms = "";
        String ss = "";
        int h = time / 3600;
        int m = (time / 60) - (h * 60);
        int s = (time - h * 3600 - m * 60) % 60;
        if (h > 0) {
            hs = h < 10 ? "0" + h : h + "";
            ms = m < 10 ? "0" + m : m + "";
            ss = s < 10 ? "0" + s : s + "";
            return hs + ":" + ms + ":" + ss;
        } else {
            ms = m < 10 ? "0" + m : m + "";
            ss = s < 10 ? "0" + s : s + "";
            return ms + ":" + ss;
        }
    }

    /**
     * @param stime 输入标准时间戳，输出能显示的事件，“XX分钟前”之类的
     * @return
     */
    public static String getOppositeTime(String stime) {
        try {
            SimpleDateFormat hhmm = new SimpleDateFormat("HH:mm");
            SimpleDateFormat yyMMdd = new SimpleDateFormat("yy-MM-dd");
            SimpleDateFormat MMdd = new SimpleDateFormat("MM-dd");
            long cTime = System.currentTimeMillis() / 1000;
            long sTime = Long.parseLong(stime);
            // 如果是未来时间就显示0
            if (sTime > cTime) {
                sTime = cTime;
            }
            long dTime = cTime - sTime;
            float dDay = dTime / 3600f / 24f;
            // normal：n秒前，n分钟前，n小时前，日期
            if (dTime < 60) {
                return dTime + "秒前";
            } else if (dTime < 3600) {
                return dTime / 60 + "分钟前";
            } else if (dTime >= 3600 && dDay <= 1) {
                return dTime / 3600 + "小时前";
            } else if (inLastDay(sTime, cTime * 1000)) {
                return "昨天" + hhmm.format(new Date(sTime * 1000));
            } else {
                Date date = new Date(sTime * 1000);
                Calendar calendar1 = Calendar.getInstance();
                calendar1.setTime(date);
                int year1 = calendar1.get(Calendar.YEAR);

                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(new Date(cTime * 1000));
                int year2 = calendar2.get(Calendar.YEAR);

                if (year1 == year2) {
                    return MMdd.format(date);
                } else {
                    return yyMMdd.format(date);
                }
            }
        } catch (Exception e) {
            return "";
        }
    }

    public static String getEventTime(String stime) {
        if (TextUtils.isEmpty(stime))
            return "";
        try {
            long sTime = Long.parseLong(stime);
            SimpleDateFormat mmddFormat = new SimpleDateFormat("M.d");
            Date date = new Date(sTime * 1000);
            return mmddFormat.format(date);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean inLastDay(long stime, long ctime) {
        Date date = new Date(ctime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        date = calendar.getTime();
        Timestamp ts = new Timestamp(date.getTime());
        return stime > ts.getTime() / 1000;
    }

    public static String dataToLong(String time) {
        long newTime = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            newTime = sdf.parse(time).getTime() / 1000;
            return String.valueOf(newTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static float getTextWidth(String source, float size) {
        Paint paint = new Paint();
        paint.setTextSize(size);
        return paint.measureText(source);
    }


    public static String getFormatedDate(String time) {
        try {
            Date date = new Date(Long.parseLong(time) * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getOppositeTimeMouth(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("M月dd日");
        try {
            return sdf.format(new Date(Long.parseLong(time) * 1000));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getFromJson(JSONObject json, String name) {
        try {
            String str = json.getString(name);
            if (str == null) str = "";
            return str;
        } catch (Exception e) {
            return "";
        }
    }

    public static String getFromJson(JSONObject json, String obname, String name) {
        try {
            String str = json.getJSONObject(obname).getString(name);
            return str;
        } catch (Exception e) {
            return "";
        }
    }

    public static Boolean getBoolean(String source) {
        try {
            if (source == null) return false;
            return Boolean.valueOf(source);
        } catch (Exception e) {
            return false;
        }
    }

    public static String getString(Boolean source) {
        try {
            return String.valueOf(source);
        } catch (Exception e) {
            return "false";
        }
    }

    public static String getString(int source) {
        try {
            return String.valueOf(source);
        } catch (Exception e) {
            return "10";
        }
    }

    public static int getInt(String source) {
        try {
            if (source == null) return 10;
            else {
                int temp = Integer.parseInt(source);
                return temp;
            }
        } catch (Exception e) {
            return 10;
        }
    }

    public static int getInt(Intent intent, String key) {
        try {
            if (intent == null) return 0;
            else {
                int temp = intent.getIntExtra(key, 0);
                return temp;
            }
        } catch (Exception e) {
            return 0;
        }
    }

    public static int getInt(Bundle bundle, String key) {
        try {
            if (bundle == null) return 0;
            else {
                int temp = bundle.getInt(key, 0);
                return temp;
            }
        } catch (Exception e) {
            return 0;
        }
    }

    public static Boolean getBoolean(Bundle bundle, String key) {
        try {
            if (bundle == null) return false;
            else {
                Boolean temp = bundle.getBoolean(key, false);
                return temp;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public static Boolean getBoolean(Intent intent, String key) {
        try {
            if (intent == null) return false;
            else {
                Boolean tempString = intent.getBooleanExtra(key, false);
                if (tempString == null) tempString = false;

                return tempString;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public static Boolean getHaveDingBoolean(Timeline mItem) {
        try {
            if (mItem == null) return false;
            else {
                Boolean tempString = Boolean.valueOf(mItem.getHaveDing());
                if (tempString == null) tempString = true;

                return tempString;
            }
        } catch (Exception e) {
            return false;
        }
    }


    public static String getString(Intent intent, String key) {
        try {
            if (intent == null) return "";
            else {
                String tempString = intent.getStringExtra(key);
                if (tempString == null) tempString = "";

                return tempString;
            }
        } catch (Exception e) {
            return "";
        }
    }

    public static String getString(Bundle bundle, String key) {
        try {
            if (bundle == null) return "";
            else {
                String tempString = bundle.getString(key);
                if (tempString == null) tempString = "";

                return tempString;
            }
        } catch (Exception e) {
            return "";
        }
    }

    public static String getString(Bundle bundle, String key, String defaultvalue) {
        try {
            if (bundle == null) return defaultvalue;
            else {
                String tempString = bundle.getString(key);
                if (TextUtils.isEmpty(tempString)) tempString = defaultvalue;
                return tempString;
            }
        } catch (Exception e) {
            return defaultvalue;
        }
    }

    public static String notNull(String object) {
        if (object == null) return "";
        else return object;
    }

    public static Boolean notNullTrue(String object) {
        if (TextUtils.isEmpty(object)) return false;
        return Boolean.valueOf(object);
    }

    public static Boolean notNullEqual(String object, String standerd) {
        if (TextUtils.isEmpty(object)) return false;
        if (TextUtils.isEmpty(standerd)) return false;
        return object.equals(standerd);
    }

    public static Boolean notNullStartWith(String object, String standerd) {
        if (TextUtils.isEmpty(object)) return false;
        return object.startsWith(standerd);
    }

    public static Boolean notNullStartWithUrlHead(String object) {
        if (TextUtils.isEmpty(object)) return false;
        return object.startsWith(HttpUtils.URL_HEAD) || object.startsWith(HttpUtils.HTTPS_HEAD);
    }

    public static Boolean notNullEndWith(String object, String standerd) {
        try {
            if (TextUtils.isEmpty(object)) return false;
            return object.endsWith(standerd);
        } catch (Exception e) {
            return false;
        }
    }

    public static int parseHourToInt(String hour) {
        try {
            String[] array = hour.split(":");
            return Integer.parseInt(array[0]) * 100 + Integer.parseInt(array[1]);
        } catch (Exception e) {
            return 0;
        }
    }

    public static SpannableString setAtUser(String tempStr, List<AtUser> at_users, Context context) {
        SpannableString sps = new SpannableString(tempStr);
        if (null == at_users)
            return sps;
        for (AtUser a : at_users) {
            String temp = "@" + a.getUname();
            temp = Pattern.quote(temp);
            Pattern pattern = Pattern.compile(temp);
            Matcher matcher = pattern.matcher(tempStr);
            while (matcher.find()) {
                int start = matcher.start();
                int end = matcher.end();
                NoLineClickSpan no = new NoLineClickSpan(a.getUid(), context);
                sps.setSpan(no, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return sps;
    }

}